package com.artisan.springuitls;

import com.artisan.springuitls.demos.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.Scanner;

/**
 * Spring 官方工具类演示运行器
 * 
 * 20 个 Spring 官方工具类完整演示
 * 作者：一位深耕 Spring 生态 5 年的开发者
 */
@Component
public class SpringUtilsDemoRunner implements CommandLineRunner {

    @Autowired private StringUtilsDemo stringUtilsDemo;
    @Autowired private CollectionUtilsDemo collectionUtilsDemo;
    @Autowired private ObjectUtilsDemo objectUtilsDemo;
    @Autowired private AssertDemo assertDemo;
    @Autowired private FileCopyUtilsDemo fileCopyUtilsDemo;
    @Autowired private StreamUtilsDemo streamUtilsDemo;
    @Autowired private ResourceUtilsDemo resourceUtilsDemo;
    @Autowired private ReflectionUtilsDemo reflectionUtilsDemo;
    @Autowired private AopProxyUtilsDemo aopProxyUtilsDemo;
    @Autowired private DigestUtilsDemo digestUtilsDemo;
    @Autowired private Base64UtilsDemo base64UtilsDemo;
    @Autowired private StopWatchDemo stopWatchDemo;
    @Autowired private AntPathMatcherDemo antPathMatcherDemo;
    @Autowired private MimeTypeUtilsDemo mimeTypeUtilsDemo;
    @Autowired private UriComponentsBuilderDemo uriComponentsBuilderDemo;
    @Autowired private ClassUtilsDemo classUtilsDemo;
    @Autowired private SystemPropertyUtilsDemo systemPropertyUtilsDemo;
    @Autowired private NumberUtilsDemo numberUtilsDemo;
    @Autowired private ConcurrentReferenceHashMapDemo concurrentReferenceHashMapDemo;
    @Autowired private LinkedMultiValueMapDemo linkedMultiValueMapDemo;

    @Override
    public void run(String... args) throws Exception {
        printWelcome();
        
        if (args.length > 0 && "all".equals(args[0])) {
            // 运行所有演示
            runAllDemos();
        } else {
            // 交互式菜单
            showInteractiveMenu();
        }
    }

    /**
     * 打印欢迎信息
     */
    private void printWelcome() {
        System.out.println("\n");
        System.out.println("╔═══════════════════════════════════════════════════════════════╗");
        System.out.println("║                                                               ║");
        System.out.println("║   Spring Boot 开发必备：20 个官方工具类深度实战              ║");
        System.out.println("║   告别重复造轮子，提升开发效率 50%+                          ║");
        System.out.println("║                                                               ║");
        System.out.println("╚═══════════════════════════════════════════════════════════════╝");
        System.out.println();
    }

    /**
     * 运行所有演示
     */
    private void runAllDemos() throws Exception {
        System.out.println("========== 开始运行所有演示 ==========\n");
        
        // 1. 字符串工具
        stringUtilsDemo.validateNickname("张三");
        stringUtilsDemo.demonstrateMoreMethods();
        
        // 2. 集合工具
        collectionUtilsDemo.processTags(Arrays.asList("Java", "Spring", "Boot"));
        collectionUtilsDemo.demonstrateMoreMethods();
        
        // 3. 对象工具
        objectUtilsDemo.logUserInfo(new ObjectUtilsDemo.User("李四", 30));
        objectUtilsDemo.demonstrateMoreMethods();
        
        // 4. 断言工具
        assertDemo.cancelOrder(1001L);
        assertDemo.demonstrateMoreAssertions();
        
        // 5. 文件拷贝工具
        fileCopyUtilsDemo.demonstrateMoreMethods();
        fileCopyUtilsDemo.simulateFileUpload();
        
        // 6. 流工具
        streamUtilsDemo.demonstrateMoreMethods();
        streamUtilsDemo.demonstrateHttpResponse();
        
        // 7. 资源工具
        resourceUtilsDemo.loadResource();
        resourceUtilsDemo.demonstrateProtocols();
        
        // 8. 反射工具
        reflectionUtilsDemo.testPrivateMethod();
        reflectionUtilsDemo.demonstrateFieldOperations();
        
        // 9. AOP 代理工具
        aopProxyUtilsDemo.analyzeProxy();
        aopProxyUtilsDemo.demonstrateProxyDetection();
        
        // 10. 摘要工具
        digestUtilsDemo.encodePassword("123456");
        digestUtilsDemo.demonstrateDigestAlgorithms();
        
        // 11. Base64 工具
        base64UtilsDemo.encodeImage("测试图片".getBytes(java.nio.charset.StandardCharsets.UTF_8));
        base64UtilsDemo.demonstrateBasicOperations();
        
        // 12. 性能监控
        stopWatchDemo.monitorOperations();
        stopWatchDemo.demonstrateBasicUsage();
        
        // 13. 路径匹配
        antPathMatcherDemo.matchUrl("/api/user/1001/profile");
        antPathMatcherDemo.demonstrateBasicMatching();
        
        // 14. MIME 类型
        mimeTypeUtilsDemo.resolveMimeType("application/json");
        mimeTypeUtilsDemo.demonstrateCommonMimeTypes();
        
        // 15. URI 构建
        uriComponentsBuilderDemo.buildUrl();
        uriComponentsBuilderDemo.demonstrateBasicUriBuilding();
        
        // 16. 类工具
        classUtilsDemo.isRedisAvailable();
        classUtilsDemo.demonstrateClassPresence();
        
        // 17. 系统属性
        systemPropertyUtilsDemo.resolvePath("${user.home}/app/logs");
        systemPropertyUtilsDemo.demonstrateCommonProperties();
        
        // 18. 数字工具
        numberUtilsDemo.safeParseInt("123");
        numberUtilsDemo.demonstrateNumberParsing();
        
        // 19. 并发引用 Map
        concurrentReferenceHashMapDemo.demonstrateLightweightCache();
        concurrentReferenceHashMapDemo.demonstrateBasicOperations();
        
        // 20. 多值 Map
        linkedMultiValueMapDemo.processForm();
        linkedMultiValueMapDemo.demonstrateHttpParameters();
        
        System.out.println("\n========== 所有演示运行完成 ==========\n");
    }

    /**
     * 显示交互式菜单
     */
    private void showInteractiveMenu() throws Exception {
        try (Scanner scanner = new Scanner(System.in)) {
            while (true) {
            printMenu();
            System.out.print("请选择要演示的工具类编号（0-20，或输入 q 退出）: ");
            String input = scanner.nextLine().trim();
            
            if ("q".equalsIgnoreCase(input) || "quit".equalsIgnoreCase(input)) {
                System.out.println("\n感谢使用！再见！\n");
                break;
            }
            
            try {
                int choice = Integer.parseInt(input);
                runDemo(choice);
                } catch (NumberFormatException e) {
                    System.out.println("\n⚠️ 无效输入，请输入数字 0-20 或 q 退出\n");
                }
            }
        }
    }

    /**
     * 打印菜单
     */
    private void printMenu() {
        System.out.println("\n========== 工具类演示菜单 ==========");
        System.out.println("  0. 运行所有演示");
        System.out.println();
        System.out.println("【核心工具】");
        System.out.println("  1. StringUtils - 字符串处理终结者");
        System.out.println("  2. CollectionUtils - 集合操作防坑神器");
        System.out.println("  3. ObjectUtils - 对象安全操作卫士");
        System.out.println("  4. Assert - 参数校验断言大师");
        System.out.println();
        System.out.println("【文件和流】");
        System.out.println("  5. FileCopyUtils - 文件拷贝终极方案");
        System.out.println("  6. StreamUtils - 流操作轻量级专家");
        System.out.println("  7. ResourceUtils - 资源路径解析器");
        System.out.println();
        System.out.println("【反射和 AOP】");
        System.out.println("  8. ReflectionUtils - 反射操作安全网");
        System.out.println("  9. AopProxyUtils - AOP 代理解密器");
        System.out.println();
        System.out.println("【加密和编码】");
        System.out.println(" 10. DigestUtils - 加密工具精简版");
        System.out.println(" 11. Base64Utils - Base64 编解码专家");
        System.out.println();
        System.out.println("【性能和路径】");
        System.out.println(" 12. StopWatch - 代码耗时统计器");
        System.out.println(" 13. AntPathMatcher - 路径匹配引擎");
        System.out.println();
        System.out.println("【Web 工具】");
        System.out.println(" 14. MimeTypeUtils - MIME 类型解析器");
        System.out.println(" 15. UriComponentsBuilder - URL 构建安全专家");
        System.out.println();
        System.out.println("【其他工具】");
        System.out.println(" 16. ClassUtils - 类操作安全助手");
        System.out.println(" 17. SystemPropertyUtils - 系统属性占位符解析器");
        System.out.println(" 18. NumberUtils - 数字转换安全卫士");
        System.out.println(" 19. ConcurrentReferenceHashMap - 并发弱引用 Map");
        System.out.println(" 20. LinkedMultiValueMap - 多值 Map 实现");
        System.out.println("====================================");
    }

    /**
     * 运行指定的演示
     */
    private void runDemo(int choice) throws Exception {
        switch (choice) {
            case 0:
                runAllDemos();
                break;
            case 1:
                stringUtilsDemo.validateNickname("  张三  ");
                stringUtilsDemo.demonstrateMoreMethods();
                break;
            case 2:
                collectionUtilsDemo.processTags(Arrays.asList("Java", "Spring"));
                collectionUtilsDemo.demonstrateMoreMethods();
                break;
            case 3:
                objectUtilsDemo.logUserInfo(new ObjectUtilsDemo.User("李四", 30));
                objectUtilsDemo.demonstrateMoreMethods();
                break;
            case 4:
                assertDemo.cancelOrder(1001L);
                assertDemo.demonstrateMoreAssertions();
                break;
            case 5:
                fileCopyUtilsDemo.demonstrateMoreMethods();
                break;
            case 6:
                streamUtilsDemo.demonstrateMoreMethods();
                break;
            case 7:
                resourceUtilsDemo.loadResource();
                resourceUtilsDemo.demonstrateProtocols();
                break;
            case 8:
                reflectionUtilsDemo.testPrivateMethod();
                reflectionUtilsDemo.demonstrateFieldOperations();
                break;
            case 9:
                aopProxyUtilsDemo.analyzeProxy();
                aopProxyUtilsDemo.printBestPractices();
                break;
            case 10:
                digestUtilsDemo.encodePassword("123456");
                digestUtilsDemo.demonstrateDigestAlgorithms();
                break;
            case 11:
                base64UtilsDemo.demonstrateBasicOperations();
                base64UtilsDemo.demonstrateUrlSafeEncoding();
                break;
            case 12:
                stopWatchDemo.monitorOperations();
                stopWatchDemo.demonstrateBasicUsage();
                break;
            case 13:
                antPathMatcherDemo.matchUrl("/api/user/1001");
                antPathMatcherDemo.demonstrateBasicMatching();
                break;
            case 14:
                mimeTypeUtilsDemo.demonstrateCommonMimeTypes();
                mimeTypeUtilsDemo.demonstrateMimeTypeParsing();
                break;
            case 15:
                uriComponentsBuilderDemo.buildUrl();
                uriComponentsBuilderDemo.demonstrateBasicUriBuilding();
                break;
            case 16:
                classUtilsDemo.isRedisAvailable();
                classUtilsDemo.demonstrateClassPresence();
                break;
            case 17:
                systemPropertyUtilsDemo.resolvePath("${user.home}/logs");
                systemPropertyUtilsDemo.demonstrateCommonProperties();
                break;
            case 18:
                numberUtilsDemo.safeParseInt("123");
                numberUtilsDemo.demonstrateNumberParsing();
                break;
            case 19:
                concurrentReferenceHashMapDemo.demonstrateLightweightCache();
                concurrentReferenceHashMapDemo.demonstrateBasicOperations();
                break;
            case 20:
                linkedMultiValueMapDemo.processForm();
                linkedMultiValueMapDemo.demonstrateHttpParameters();
                break;
            default:
                System.out.println("\n⚠️ 无效选择，请输入 0-20 之间的数字\n");
        }
    }
}

